package com.zhuiyun.pm.client.bid.chat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.MyObjectDdd;
import com.zhuiyun.pm.client.action.entity.GoodsEntity;
import com.zhuiyun.pm.client.action.mapper.GoodsMapper;
import com.zhuiyun.pm.client.bid.chat.entity.BidRecord;
import com.zhuiyun.pm.client.bid.chat.entity.Email;
import com.zhuiyun.pm.client.bid.chat.entity.OrderInfo;
import com.zhuiyun.pm.client.bid.chat.mapper.BidRecordMapper;
import com.zhuiyun.pm.client.bid.chat.service.BidRecordService;
import com.zhuiyun.pm.client.login.entity.ClientUser;
import com.zhuiyun.pm.client.login.mapper.UserLoginDao;
import com.zhuiyun.pm.result.CommonResult;
import com.zhuiyun.pm.utils.MailUtils;
import com.zhuiyun.pm.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName BidRecordController
 * @Description 操作拍卖进行时的数据记录
 * @Author lyp
 * @Date 2023/3/15 10:30
 **/
@RestController
@RequestMapping("/BidRecordController")
@CrossOrigin
public class BidRecordController {

    @Autowired
    BidRecordService bidRecordService;

    @Autowired
    BidRecordMapper bidRecordMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    UserLoginDao userLoginDao;


    /**
     * @author lyp
     * @description 保存拍卖出价记录
     * @date 2023/3/16 10:44
     * @param
     * @return CommonResult
     */
    @PostMapping("/saveBidRecord")
    public CommonResult saveBidRecord(@RequestBody String roomId){
        if(roomId != null){
            String key = "room" + roomId;
            return bidRecordService.insertList(key);
        }else{
            return CommonResult.error("房间id不能为空");
        }
    }

    /**
     * @author lyp
     * @description 得到当前物品的价格
     * @date 2023/3/16 9:51
     * @param
     * @return CommonResult
     */
    @GetMapping("/getCurrentPrice")
    public CommonResult getCurrentPrice(String key){
        Object obj = redisUtil.get("AUCTION:PRICE:ROOM_AUCTION_PRICE_room" + key);
        if(obj != null){
            return CommonResult.ok(obj);
        }else{
            String key1 = "room" + key;
            BidRecord maxBid = bidRecordMapper.getMaxBid(key1);
            if(maxBid != null){
                return CommonResult.ok(maxBid.getMaxBid());
            }else{
                return CommonResult.error("请联系管理员");
            }
        }
    }

    /**
     * @author lyp
     * @description 得到历史出价记录
     * @date 2023/3/16 14:33
     * @param
     * @return CommonResult
     */
    @GetMapping("/getRecordOfBid")
    public CommonResult getRecordOfBid(String roomId){
        List<Object> objectList = redisUtil.lGet("AUCTION:BIDRECORD:BID_RECORD_room"+roomId, 0, -1);
        List<BidRecord> list = (List<BidRecord>)(List)objectList;
        if(!CollectionUtils.isEmpty(list)){
            return CommonResult.ok(list);
        }else{
            List<BidRecord> recordOfBid = bidRecordMapper.getRecordOfBid(roomId);
            if(!CollectionUtils.isEmpty(recordOfBid)){
                return CommonResult.ok(recordOfBid);
            }else{
                return CommonResult.error("请联系管理员");
            }
        }
    }

    /**
     * @author lyp
     * @description 保存拍卖结束的各种信息行成订单
     * @date 2023/3/19 20:44
     * @param
     * @return CommonResult
     */
    @PostMapping("/saveOrder")
    public CommonResult saveOrder(@RequestBody OrderInfo orderInfo){
        int i = bidRecordService.saveEndOfAuctionInfo(orderInfo);
        if(i>0){
            return CommonResult.ok("添加成功");
        }else{
            return CommonResult.error("添加失败");
        }
    }
    /**
     * @description:拍卖结束
     * @author: dongdong
     * @date: 2023/4/2 19:43
     * @param: [orderInfo]
     * @return: com.zhuiyun.pm.result.CommonResult
    **/
//    @GetMapping("/auctionClose")
//    public CommonResult auctionClose(Integer id){
//        int i = bidRecordService.auctionClose(id);
//        if(i>0){
//            return CommonResult.ok("添加成功");
//        }else{
//            return CommonResult.error("添加失败");
//        }
//    }
    /**
     * @author lyp
     * @description 根据物品id查询物品信息
     * @date 2023/3/23 19:05
     * @param: id
     * @return CommonResult
     */
    @GetMapping("/getItemInfoById")
    public CommonResult getItemInfoById(Integer id) {
        if(id != null){
            GoodsEntity itemInfoById = bidRecordService.getItemInfoById(id);
            return CommonResult.ok(itemInfoById);
        }else{
            return CommonResult.error("id不能为空");
        }
    }

    /**
     * @author lyp
     * @description 给竞价最高者发送竞价成功消息
     * @date 2023/3/27 16:20
     * @param: email
     * @return CommonResult
     */
    @PostMapping("/sendEmail")
    public CommonResult sendEmail(@RequestBody Email email){
        if(email.getUserId() != null){
            String userEmail = userLoginDao.getUserEmail(email.getUserId());
            if(!userEmail.isEmpty() && userEmail != null){
                MailUtils.sendMail(userEmail,"随心拍卖：","恭喜您，在随心拍卖网中拍卖的商品" +
                        email.getProductName() +"，最终您以" + email.getPrice() +"的价格成为本商品的获得者，请您关注‘我的竞价-订单’模块关注您的成交物品状态");
            }else{
                return CommonResult.error("用户邮箱不能为空");
            }
        }else{
            return CommonResult.error("用户id不能为空");
        }
        return CommonResult.ok();
    }

    /**
     * @author lyp
     * @description 查询拍卖中的商品按钮状态
     * @date 2023/4/1 11:07
     * @param
     * @param: goodsId
     * @return CommonResult
     */
    @GetMapping("/getButtonStatus")
    public CommonResult getButtonStatus(Integer goodsId){
        if(goodsId != null && goodsId != 0){
            Integer button = goodsMapper.getButton(goodsId);
            return CommonResult.ok(button);
        }else{
            return CommonResult.error("物品id不能为空");
        }
    }

    /**
     * @author lyp
     * @description 修改商品状态
     * @date 2023/4/1 13:58
     * @param
     * @param: id
     * @return CommonResult
     */
    @PostMapping("/updateStatus")
    public CommonResult updateStatus(@RequestBody Integer goodsId){
        if(goodsId!=null){
            int i = goodsMapper.updateStatus(goodsId);
            if(i>0){
                return CommonResult.ok();
            }else{
                return CommonResult.error("商品状态修改失败");
            }
        }else{
            return CommonResult.error("商品id不能为空");
        }
    }

    /**
     * @author lyp
     * @description 拍卖结束得出出价最高者的信息
     * @date 2023/4/1 19:03
     * @param
     * @param: id
     * @return CommonResult
     */
    @GetMapping("/getGainer")
    public CommonResult getGainer(Integer id){
        if(id!=null && id !=0){
            List<Object> objectList = redisUtil.lGet("AUCTION:BIDRECORD:BID_RECORD_room" + id, 0, -1);
            List<BidRecord> bidRecordList = (List<BidRecord>)(List)objectList;
//            int max = bidRecordList.stream()
//                    .mapToInt(obj -> obj.getBid()) // 将对象转换为"int"类型的流
//                    .max() // 获取最大值
//                    .orElse(0); // 如果列表为空则默认最大值为0
//            System.out.println("max:" + max);
            Optional<BidRecord> maxObj = bidRecordList.stream()
                    .collect(Collectors.maxBy(Comparator.comparingInt(obj -> obj.getBid())));
            return CommonResult.ok(maxObj);
        }else{
            return CommonResult.error("物品id不能为空");
        }
    }
}
